package com.tanhua.dubbo.api.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.dubbo.pojo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

@DubboService(version = "1.0.0")
public class VisitorsApiImpl implements VisitorsApi {

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String saveVisitor(Long userId, Long visitorUserId, String from) {
        //判断该访客今日是否已经访问过
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();

        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("visitorUserId").is(visitorUserId)
                .andOperator(Criteria.where("date").lte(maxDate), //同一个字段添加多个条件时需要使用andOperator()
                        Criteria.where("date").gte(minDate))
        );

        Visitors visitors = this.mongoTemplate.findOne(query, Visitors.class);
        if (null != visitors) {
            //TODO 更新用户信息（选择性）
            return null;
        }

        //记录访客信息
        visitors = new Visitors();
        visitors.setId(ObjectId.get());
        visitors.setUserId(userId);
        visitors.setVisitorUserId(visitorUserId);
        visitors.setDate(System.currentTimeMillis());
        visitors.setFrom(from);
        this.mongoTemplate.save(visitors);

        return visitors.getId().toString();
    }

    @Override
    public List<Visitors> queryMyVisitor(Long userId) {
        PageRequest pageRequest = PageRequest.of(0, 5, Sort.by(Sort.Order.desc("date")));
        Criteria criteria = Criteria.where("userId").is(userId);
        //查询该用户上一次查询列表的时间
        //TODO 查询列表的时间，在项目实战中查询列表中写入
        String hashKey = Convert.toStr(userId);
        Object lastDate = this.redisTemplate.opsForHash().get(VISITOR_REDIS_KEY, hashKey);
        if(null != lastDate){
            criteria.and("date").gte(Convert.toLong(lastDate));
        }

        Query query = Query.query(criteria).with(pageRequest);
        return this.mongoTemplate.find(query, Visitors.class);
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }


}
